<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
          <PageTools>
            <!-- 插入到left插槽位置 -->
            <template #left>
              <span>总记录数：100条</span>
            </template>
            <!-- 插入到right插槽位置 -->
            <template #right>
              <el-button
                type="warning"
                size="small"
                @click="$router.push('/import')"
              >
                导入excel
              </el-button>
              <el-button
                type="danger"
                size="small"
                :loading="downloadLoading"
                @click="exportData"
              >
                导出excel
              </el-button>
              <el-button
                v-if="canClick('p-em-add')"
                type="primary"
                size="small"
                @click="showDialog = true"
              >
                新增员工
              </el-button>
            </template>
          </PageTools>
        </div>
        <div>
          <!-- table列表 -->
          <el-table border :data="list">
            <el-table-column label="序号" type="index" />
            <el-table-column label="姓名" prop="username" />
            <el-table-column label="头像" prop="staffPhoto">
              <template #default="{ row }">
                <img
                  class="staff"
                  :src="row.staffPhoto"
                  @click="showErweima(row.staffPhoto)"
                />
              </template>
            </el-table-column>
            <el-table-column label="工号" prop="workNumber" />
            <el-table-column label="聘用形式" prop="formOfEmployment">
              <template #default="{ row }">
                {{ getEmployeeType(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column label="部门" prop="departmentName" />
            <el-table-column label="入职时间">
              <template #default="{ row }">
                {{ formatetime(row.correctionTime) }}
              </template>
            </el-table-column>
            <el-table-column label="账户状态" prop="">
              <el-switch
                v-model="qs"
                :active-value="true"
                :inactive-value="false"
              />
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
              <template #default="{ row }">
                <el-button
                  type="text"
                  size="small"
                  @click="getdetailes(row.id)"
                >
                  查看
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="distributeRole(row)"
                >
                  分配角色
                </el-button>
                <el-button type="text" size="small" @click="delEmp(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row
            type="flex"
            justify="center"
            align="middle"
            style="height: 60px"
          >
            <el-pagination
              layout="prev, pager, next,sizes"
              :page-size="params.size"
              :total="total"
              :page-sizes="[10, 5, 15]"
              @size-change="changeSize"
              @current-change="changePage"
            />
          </el-row>
        </div>
      </el-card>
    </div>
    <add-employees
      :show-dialog="showDialog"
      @close-pop="showDialog = $event"
      @get-list="getEmployee"
    />
    <el-dialog
      title="二维码"
      :visible="erweima"
      width="13%"
      @close="erweima = false"
    >
      <canvas ref="myCanvas" />
    </el-dialog>
    <attribute-role ref="atrributerole" :showattribute.sync="showattribute" />
  </div>
</template>

<script>

import { getEmployeeList, delEmployee } from '@/api/employees'
import EnumType from '@/api/constant/employees'
import { formatetime } from '@/utils/index'
import AddEmployees from './components/addEmployees.vue'
import QrCode from 'qrcode'
import AttributeRole from './components/attribute-role.vue'
export default {
  components: {
    AddEmployees,
    AttributeRole
  },
  data () {
    return {
      showattribute: false,
      erweima: false,
      downloadLoading: false,
      showDialog: false,
      qs: true,
      params: { page: 1, size: 10 },
      total: 0,
      list: []
    }
  },
  created () {
    this.getEmployee()
  },
  methods: {
    distributeRole (row) {
      this.$refs.atrributerole.getSelectedRole(row.id)
      this.showattribute = true
    },
    showErweima (photo) {
      if (photo) {
        this.erweima = true
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, photo)
        })
      }
    },
    closeErweima () {
      this.erweima = false
      console.log(this.erweima)
    },
    getdetailes (id) {
      this.$router.push(`/employees/detail/${id}`)
    },
    async exportData () {
      // 1. 开始导出
      this.downloadLoading = true
      // 2. 使用Excel导出插件导出数据（核心）
      // import('@/utils/Export2Excel') 按需加载一个js模块（懒加载）
      const excel = await import('@/vender/Export2Excel')
      console.log('excel导出方法：', excel)
      const userheader = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      const header = Object.keys(userheader) // 导出数据的表头
      const enheader = Object.values(userheader)

      const data = this.transfromListtoArr(this.list, enheader)
      console.log(data)
      excel.export_json_to_excel({
        // 表头 必填
        header,

        // 表头对应的具体数据 必填
        data,
        filename: `elm-list-${Date.now()}`, // 导出下载的文件名称
        autoWidth: true, // 导出excel列宽度是否自适应
        bookType: 'xlsx' // 导出生成的文件类型
      })
      // 3. 导出成功关闭loading
      this.downloadLoading = false
    },
    transfromListtoArr (list, enheader) {
      const arr = []
      list.forEach(item => {
        const newarr2 = []
        for (const key in item) {
          if (enheader.includes(key)) {
            if (key === 'formOfEmployment') {
              newarr2.push(this.getEmployeeType(item[key]))
              continue
            }
            newarr2.push(item[key])
          }
        }
        arr.push(newarr2)
      })
      return arr
    },
    async delEmp (row) {
      try {
        await this.$confirm(`确认删除${row.username}吗`, '提示')
        await delEmployee(row.id)
        const pageNum = (this.total - 1) / this.params.size
        console.log(pageNum)
        if (pageNum > 0) {
          this.params.page = pageNum
        }
        this.getEmployee()
        this.$message.success('删除成功')
        this.params.page = 1
      } catch (error) {
        console.log(error)
      }
    },
    formatetime,
    getEmployeeType (type) {
      const map = {}
      EnumType.hireType.forEach(item => {
        map[item.id] = item.value
      })
      return map[type]
    },
    changeSize (size) {
      this.params.size = size
      this.getEmployee()
    },
    changePage (page) {
      this.params.page = page
      this.getEmployee(this.params)
    },
    async getEmployee () {
      try {
        const res = await getEmployeeList(this.params)
        this.total = res.total
        this.list = res.rows
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 100%;
  }
}
</style>
